-- Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
--
-- this file licensed under the Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
--
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
-- PURPOSE.
-- See the Mulan PSL v2 for more details.

local class = require 'mc.class'
local log = require 'mc.logging'
local json = require 'cjson'
local mdb_config_manage = require 'mc.mdb.micro_component.config_manage'

local utils = require 'power_mgmt_utils'
local customize_config = require 'config_mgmt.customize_config'

local server = class()

function server:ctor(db, bus)
    self.db = db
    self.bus = bus
end

function server:init()
    self:register()
end

-- 配置导入
function server:on_import(ctx, data_str, data_type)
    local data
    if data_str then
        data = json.decode(data_str)
    end
    if not data or not data.ConfigData or type(data.ConfigData) ~= 'table' then
        log:error('Import data [%s] is invalid', data_str)
        utils.operation_log(ctx, "Import configuration failed")
        return
    end

    if data_type == 'custom' then
        if not data.ConfigData.CustomSettings or type(data.ConfigData.CustomSettings) ~= 'table' then
            log:error('Import data [%s] is invalid', data_str)
            utils.operation_log(ctx, "Import configuration failed")
            return
        end
        customize_config.on_import(self, ctx, data.ConfigData.CustomSettings)
    else
        log:error('Import type [%s] is invalid', data_type)
        utils.operation_log(ctx, "Import configuration failed")
    end
    log:notice('Import successfully!')
end

-- 配置导出
function server:on_export(ctx, type)
    local data = {}
    if type == 'custom' then
        local ret = customize_config.on_export(self, ctx)
        data.CustomSettings = ret
        log:error('Export data [%s] is custom', ret)
    else
        log:error('Export type [%s] is invalid', type)
    end
    log:notice('Export successfully!')
    return json.encode({ ConfigData = data })
end

function server:register()
    mdb_config_manage.on_import(function(...) return self:on_import(...) end)
    mdb_config_manage.on_export(function(...) return self:on_export(...) end)
end

return server
